/**
 * 动态转静态 - 执行器
 * 将动态生成的题目转换为静态题目
 */

const fs = require('fs');
const path = require('path');

const ROOT = path.join(__dirname, '..', '..');

// 需要转换的文件
const files = [
  'questions/middle-school/回归分析.ts',
  'questions/middle-school/实际应用.ts',
  'questions/middle-school/数学建模.ts',
  'questions/middle-school/竞赛基础.ts',
  'questions/middle-school/综合压轴题.ts'
];

function s(str) {
  return JSON.stringify(String(str)).slice(1, -1);
}

function convertFile(filePath) {
  console.log(`\n🔄 转换: ${filePath}`);
  
  const fullPath = path.join(ROOT, filePath);
  const content = fs.readFileSync(fullPath, 'utf-8');
  
  // 备份原文件
  const backupPath = fullPath.replace('.ts', '.dynamic-backup.ts');
  fs.writeFileSync(backupPath, content, 'utf-8');
  console.log(`📦 已备份到: ${backupPath}`);
  
  // 执行动态代码生成题目数组
  try {
    // 使用eval执行代码
    const code = content
      .replace(/export const /g, 'var ')
      .replace(/export default .*?;/g, '');
    
    const questions = eval(`
      (function() {
        ${code}
        // 查找题目数组变量
        const varNames = Object.keys(this).filter(k => k.includes('QUESTIONS'));
        return varNames.length > 0 ? this[varNames[0]] : [];
      }).call({})
    `);
    
    if (!Array.isArray(questions) || questions.length === 0) {
      console.log(`❌ 无法获取题目数组`);
      return { success: false, count: 0 };
    }
    
    console.log(`✅ 成功生成 ${questions.length} 题`);
    
    // 生成静态代码
    const topicName = path.basename(filePath, '.ts');
    let staticCode = `// ${topicName} - 初中数学综合题型（50题）\n`;
    staticCode += `// 已从动态生成转换为静态题目，确保准确性\n\n`;
    staticCode += `interface Question {\n`;
    staticCode += `  stem: string;\n`;
    staticCode += `  difficulty: number;\n`;
    staticCode += `  answer: (string | number)[];\n`;
    staticCode += `  hint1: string;\n`;
    staticCode += `  hint2: string;\n`;
    staticCode += `  solution: string;\n`;
    staticCode += `}\n\n`;
    staticCode += `export const ${topicName}_QUESTIONS: Question[] = [\n`;
    
    questions.forEach((q, i) => {
      // 处理answer
      let answerStr;
      if (Array.isArray(q.answer)) {
        answerStr = `[${q.answer.map(a => {
          if (typeof a === 'number') return a;
          if (Array.isArray(a)) return `[${a.join(', ')}]`;
          return `"${s(a)}"`;
        }).join(', ')}]`;
      } else {
        answerStr = `[${typeof q.answer === 'number' ? q.answer : `"${s(q.answer)}"`}]`;
      }
      
      staticCode += `  {\n`;
      staticCode += `    stem: "${s(q.stem)}",\n`;
      staticCode += `    difficulty: ${q.difficulty},\n`;
      staticCode += `    answer: ${answerStr},\n`;
      staticCode += `    hint1: "${s(q.hint1)}",\n`;
      staticCode += `    hint2: "${s(q.hint2)}",\n`;
      staticCode += `    solution: "${s(q.solution)}"\n`;
      staticCode += `  }${i < questions.length - 1 ? ',' : ''}\n`;
    });
    
    staticCode += `];\n\n`;
    staticCode += `export default ${topicName}_QUESTIONS;\n`;
    
    // 写入新文件
    fs.writeFileSync(fullPath, staticCode, 'utf-8');
    console.log(`✅ 已转换为静态题目`);
    
    return { success: true, count: questions.length };
  } catch (error) {
    console.error(`❌ 转换失败: ${error.message}`);
    console.error(error.stack);
    return { success: false, count: 0, error: error.message };
  }
}

function main() {
  console.log('🚀 开始将动态题目转换为静态题目...\n');
  console.log('目标：');
  console.log('1. 全部动态转静态');
  console.log('2. 保证每个题型足够50道题');
  console.log('3. 验证不能有错误\n');
  
  const results = [];
  
  for (const file of files) {
    const result = convertFile(file);
    results.push({ file, ...result });
  }
  
  console.log('\n' + '='.repeat(60));
  console.log('📊 转换统计：');
  console.log('='.repeat(60));
  
  const successCount = results.filter(r => r.success).length;
  const failCount = results.filter(r => !r.success).length;
  const totalQuestions = results.reduce((sum, r) => sum + (r.count || 0), 0);
  
  console.log(`成功转换: ${successCount}个文件`);
  console.log(`转换失败: ${failCount}个文件`);
  console.log(`总题目数: ${totalQuestions}题`);
  console.log('='.repeat(60));
  
  if (failCount > 0) {
    console.log('\n❌ 失败的文件：');
    results.filter(r => !r.success).forEach(r => {
      console.log(`  - ${r.file}: ${r.error || '未知错误'}`);
    });
  }
  
  console.log('\n✅ 转换完成！');
  console.log('📝 原动态文件已备份为 .dynamic-backup.ts');
  console.log('🔍 接下来将运行验证脚本检查题目准确性...');
}

main();

